//
// Created by jayyu on 2021/6/30.
//
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "../bzip2/bzlib.h"
#include "bspatch.h"

static int64_t offtin2(uint8_t *buf) {
    int64_t y;

    y = buf[7] & 0x7F;
    y = y * 256;
    y += buf[6];
    y = y * 256;
    y += buf[5];
    y = y * 256;
    y += buf[4];
    y = y * 256;
    y += buf[3];
    y = y * 256;
    y += buf[2];
    y = y * 256;
    y += buf[1];
    y = y * 256;
    y += buf[0];

    if (buf[7] & 0x80) y = -y;

    return y;
}

static int bz2_read(const struct bspatch_stream *stream, void *buffer, int length) {
    int n;
    int bz2err;
    BZFILE *bz2;

    bz2 = (BZFILE *) stream->opaque;
    n = BZ2_bzRead(&bz2err, bz2, buffer, length);
    if (n != length)
        return -1;

    return 0;
}

int do_patch(const char *sourcePath, const char *desPath, const char *patchPath) {
    FILE *f;
    int fd;
    int bz2err;
    uint8_t header[24];
    uint8_t *old, *news;
    int64_t oldsize, newsize;
    BZFILE *bz2;
    struct bspatch_stream stream;
    struct stat sb;

//    if (argc != 4) errx(1, "usage: %s oldfile newfile patchfile\n", argv[0]);

    /* Open patch file */
    if ((f = fopen(patchPath, "r")) == NULL)
        err(1, "fopen(%s)", patchPath);

    /* Read header */
    if (fread(header, 1, 24, f) != 24) {
        if (feof(f))
            errx(1, "Corrupt patch\n");
        err(1, "fread(%s)", patchPath);
    }

    /* Check for appropriate magic */
    if (memcmp(header, "ENDSLEY/BSDIFF43", 16) != 0)
        errx(1, "Corrupt patch\n");

    /* Read lengths from header */
    newsize = offtin2(header + 16);
    if (newsize < 0)
        errx(1, "Corrupt patch\n");

    /* Close patch file and re-open it via libbzip2 at the right places */
    if (((fd = open(sourcePath, O_RDONLY, 0)) < 0) ||
        ((oldsize = lseek(fd, 0, SEEK_END)) == -1) ||
        ((old = malloc(oldsize + 1)) == NULL) ||
        (lseek(fd, 0, SEEK_SET) != 0) ||
        (read(fd, old, oldsize) != oldsize) ||
        (fstat(fd, &sb)) ||
        (close(fd) == -1))
        err(1, "%s", sourcePath);
    if ((news = malloc(newsize + 1)) == NULL) err(1, NULL);

    if (NULL == (bz2 = BZ2_bzReadOpen(&bz2err, f, 0, 0, NULL, 0)))
        errx(1, "BZ2_bzReadOpen, bz2err=%d", bz2err);

    stream.read = bz2_read;
    stream.opaque = bz2;
    if (bspatch(old, oldsize, news, newsize, &stream))
        errx(1, "bspatch");

    /* Clean up the bzip2 reads */
    BZ2_bzReadClose(&bz2err, bz2);
    fclose(f);

    /* Write the news file */
    if (((fd = open(desPath, O_CREAT | O_TRUNC | O_WRONLY, sb.st_mode)) < 0) ||
        (write(fd, news, newsize) != newsize) || (close(fd) == -1))
        err(1, "%s", desPath);

    free(news);
    free(old);

    return 0;
}